package com.hxy.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库密码加密工具类
 *
 * @Author haoxuyang
 * @Date 2024/9/2 18:02
 */
public class DruidEncryptUtil {

    private static String publicKey;

    private static String privateKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            //System.out.println("privateKey：" + privateKey);
            publicKey = keyPair[1];
            //System.out.println("publicKey：" + publicKey);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     *
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        return encrypt;
    }

    /**
     * 解密
     *
     * @param encryptText
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(privateKey, encryptText);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("sdFN2kAXspLpp5nk");
        System.out.println("encrypt：" + encrypt);
    }
}
